package team.chess.server;



import team.chess.util.Config;
import team.chess.util.Request;
import team.chess.util.Response;

import java.io.*;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.*;

public class Server extends Thread{

    public String account;
    public String iP;
    public ServerSocket server = null;
    public Socket socket = null;
    OutputStream os = null;
    ObjectOutputStream oos = null;

    public Server(String account, String iP) {
        this.account = account;
        this.iP = iP;

    }

    @Override
    public void run(){
        try {
            System.out.println("!!!");
            server = new ServerSocket(6666);
            System.out.println("创建房间：房间创建成功");
            socket = server.accept();

            System.out.println(socket.isConnected());
            //数据库相关
            Connection conn = null;
            try {
                conn = DriverManager.getConnection(Config.JDBCURL, "zxeao", "123456");
                String sql = String.format("SELECT account FROM `account` WHERE (ip='%s') AND (account!='%s') ",iP,account);
                PreparedStatement statement  = conn.prepareStatement(sql);
                ResultSet res = statement.executeQuery();

                if (res.next()) {
                    System.out.println("客户端连接-------账户"+res.getString(1)+"连接成功");
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            os=socket.getOutputStream();
            oos=new ObjectOutputStream(os);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public void send(Response response){

        try {
            oos.writeObject(response);
            System.out.println("发出数据");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
